import { Popover } from 'antd';
import classNames from 'classnames';
import React, { useMemo } from 'react';
import Avatar from './Avatar';
import { YmAvatarGroupProps } from './interface';

function AvatarGroup(props: YmAvatarGroupProps) {
  const {
    prefixCls = 'ym-avatar-group',
    size = 48,
    shape = 'circle',
    groupClassName,
    groupStyle,
    maxCount,
    maxStyle,
    children,
    maxPopoverPlacement = 'top',
    maxPopoverTrigger = 'hover',
  } = props;

  let newChildrens: React.ReactElement[];
  if (children) {
    const childrens = React.Children.toArray(children); //空节点（null，undefined 以及 布尔值）将在返回的数组中被忽略掉
    newChildrens = childrens.map((child, index) => {
      const currCombineProps: {
        key: string;
        size?: number;
        shape?: 'circle' | 'square';
      } = { key: `avatar-key-${index}` };
      if (!(child as any).size) {
        currCombineProps.size = size;
      }
      if (!(child as any).shape) {
        currCombineProps.shape = shape;
      }
      return React.cloneElement(child as React.ReactElement, currCombineProps);
    });
  } else {
    newChildrens = [];
  }

  const childrenShow = useMemo<React.ReactNode>(() => {
    if (newChildrens.length <= 0) {
      return null;
    } else {
      const mountChildrenLength = newChildrens.length;
      if (maxCount && maxCount < mountChildrenLength) {
        const currChildrenShow = newChildrens.slice(0, maxCount);
        const currChildrenHiden = newChildrens.slice(
          maxCount,
          mountChildrenLength,
        );
        currChildrenShow.push(
          <Popover
            key="avatar-popover-key"
            content={currChildrenHiden}
            trigger={maxPopoverTrigger}
            placement={maxPopoverPlacement}
            overlayClassName={`${prefixCls}-popover`}
          >
            {/* Tooltip 的子元素要能接受 onMouseEnter、onMouseLeave、onFocus、onClick 事件,所以只能是原生标签 */}
            <span>
              <Avatar
                rootStyle={{
                  cursor: maxPopoverTrigger === 'click' ? 'pointer' : 'auto',
                  ...maxStyle,
                }}
                size={size}
                shape={shape}
              >{`+${currChildrenHiden.length}`}</Avatar>
            </span>
          </Popover>,
        );
        return currChildrenShow;
      }
      return newChildrens;
    }
  }, [
    maxCount,
    maxStyle,
    maxPopoverPlacement,
    maxPopoverTrigger,
    newChildrens,
    size,
    shape,
  ]);

  return (
    <div className={classNames(prefixCls, groupClassName)} style={groupStyle}>
      {childrenShow}
    </div>
  );
}

export default AvatarGroup;
